<template>
	<div>
		<el-dialog title="管理规则" v-model="state.dialog.isShowDialog" width="700px">
			<div class="system-user-search">
				<el-input size="default" class="w_150 mb15 mr10" v-model="state.Name" placeholder="显示名称" @keydown.enter="getTableData"> </el-input>
				<el-button size="default" @click="getTableData" type="primary" class="mr10 mb15"> 查询 </el-button>
				<el-button size="default" type="success" class="mr10 mb15" @click="addRule"> 新增 </el-button>
				<el-button size="default" type="info" class="mr10 mb15" @click="resetForm"> 重置 </el-button>
			</div>
			<template v-if="state.tableData.length">
				<el-form class="dialog-layout" ref="userForm" :rules="rules" :model="state.ruleForm" size="default" label-width="100px">
					<el-collapse @change="handleChange" accordion v-model="state.activeNames">
						<el-collapse-item :title="item.ruleName || '新增'" v-for="(item, index) in state.tableData" :key="index" :name="item.id">
							<el-row :gutter="35">
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="显示名称" prop="ruleName">
										<div class="flex-c-c">
											<el-input v-model="state.ruleForm.ruleName" class="w_470 mr10" placeholder="请输入显示名称" clearable></el-input>
											<el-tooltip
												class="item"
												effect="dark"
												content="规则名称，一般为中文，如'1天内设备注册次数过多或注册时间间隔过短'"
												placement="right-end"
											>
												<el-icon size="25px" color="#409eff">
													<ele-QuestionFilled />
												</el-icon>
											</el-tooltip>
										</div>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="初始得分" prop="initScore">
										<div class="flex-c-c">
											<el-input v-model="state.ruleForm.initScore" class="w_470 mr10" placeholder="请输入初始得分" clearable></el-input>
											<el-tooltip class="item" effect="dark" content="初始得分，在此基础上进行累加计算" placement="right-end">
												<el-icon size="25px" color="#409eff">
													<ele-QuestionFilled />
												</el-icon>
											</el-tooltip>
										</div>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="命中基数" prop="baseNum">
										<div class="flex-c-c">
											<el-input v-model="state.ruleForm.baseNum" class="w_470 mr10" placeholder="请输入命中基数" clearable></el-input>
											<el-tooltip class="item" effect="dark" content="配合操作符，与指标字段进行运算'" placement="right-end">
												<el-icon size="25px" color="#409eff">
													<ele-QuestionFilled />
												</el-icon>
											</el-tooltip>
										</div>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="操作符" prop="opreator">
										<el-select class="w_470 mr10" v-model="state.ruleForm.opreator" size="default">
											<el-option
												v-for="item in state.riskOpreatorList"
												:key="item.enumValue"
												:label="item.desction"
												:value="item.enumValue"
											></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="指标字段" prop="sourceField">
										<el-select class="w_470 mr10" v-model="state.ruleForm.sourceField" size="default">
											<el-option v-for="item in state.riskOpreatorList" :key="item.id" :label="item.fieldName" :value="item.fieldName"></el-option>
										</el-select>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="比率" prop="rate">
										<div class="flex-c-c">
											<el-input v-model="state.ruleForm.rate" class="w_470 mr10" placeholder="请输入比率" clearable></el-input>
											<el-tooltip
												class="item"
												effect="dark"
												content="当指标字段值过大或者过小时，对指标字段进行放大或者缩小，使命中分数更加合理"
												placement="right-end"
											>
												<el-icon size="25px" color="#409eff">
													<ele-QuestionFilled />
												</el-icon>
											</el-tooltip>
										</div>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20" prop>
									<el-form-item label="最大值" prop="max">
										<div class="flex-c-c">
											<el-input v-model="state.ruleForm.max" class="w_470 mr10" placeholder="请输入最大值" clearable></el-input>
											<el-tooltip class="item" effect="dark" content="设置该条规则最大得分值" placement="right-end">
												<el-icon size="25px" color="#409eff">
													<ele-QuestionFilled />
												</el-icon>
											</el-tooltip>
										</div>
									</el-form-item>
								</el-col>
								<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
									<el-form-item label="状态" prop="status">
										<el-switch v-model="state.ruleForm.status" :inactive-value="0" :active-value="1"> </el-switch>
									</el-form-item>
								</el-col>
							</el-row>
							<div class="dialog-btn">
								<el-button type="primary" @click="onSubmit(userForm)" size="default">确 认</el-button>
								<el-button @click="onRowDel(item.id)" size="default">删 除</el-button>
							</div>
						</el-collapse-item>
					</el-collapse>
				</el-form>
			</template>

			<el-empty v-else description="暂无数据"></el-empty>
		</el-dialog>
	</div>
</template>

<script setup lang="ts" name="systemMenuDialog">
import { reactive, onMounted, ref } from 'vue';
import { FormInstance, ElMessage, ElMessageBox } from 'element-plus';
import { RiskRuleGetPagedList, RiskRuleCreate, RiskRuleUpdate, RiskRuleDelete } from '/@/api/model/index';
import { GetEnumberOptions } from '/@/api/common/index';

// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const state = reactive({
	ruleForm: {
		ruleName: '', // 规则名称
		// checkScript: '', //检验脚本
		initScore: '', // 初始分数
		baseNum: '', //基数
		opreator: '', // 操作符
		// absName: '', // 抽象名
		rate: '', // 得分率
		max: '', // 最大值
		id: '',
		status: 0, //状态
		add: false,
	} as any,
	Name: '',
	dialog: {
		isShowDialog: false,
	},
	modelId: '',
	ActivationId: '',
	tableData: [] as any,
	riskOpreatorList: [] as any, //操作符
	activeNames: '',
});

// 打开弹窗
const openDialog = (row?: any) => {
	state.modelId = row.modelId;
	state.ActivationId = row.id;
	resetForm();
	GetFieldTypes();
	state.dialog.isShowDialog = true;
};
// 关闭弹窗
const closeDialog = () => {
	state.dialog.isShowDialog = false;
};

// 初始化表格数据
const getTableData = async () => {
	const params = {
		PageIndex: 1,
		PageSize: 9999,
		Name: state.Name,
		modelId: state.modelId,
		ActivationId: state.ActivationId,
	};

	let data = await RiskRuleGetPagedList(params);
	state.tableData = data.data.items;
};
// 新增
const addRule = () => {
	state.tableData.push({ add: true, id: Date.now() });
};
const userForm = ref<FormInstance>();
const onSubmit = async (formEl: FormInstance | undefined) => {
	if (!formEl) return;
	await formEl.validate(async (valid) => {
		if (valid) {
			const params = {
				...state.ruleForm,
				modelId: state.modelId,
				activationId: state.ActivationId,
			};
			console.log(state.ruleForm.add);

			if (!state.ruleForm.add) {
				await RiskRuleUpdate(params, state.ruleForm.id);
			} else {
				delete params.id;
				await RiskRuleCreate(params);
			}
			ElMessage.success(state.ruleForm.add ? '修改成功' : '新增成功');

			resetForm();
		}
	});
};
// 重置
const resetForm = () => {
	state.Name = '';
	state.activeNames = '';
	getTableData();
};
const requiredNumber = (rule: any, value: any, callback: any) => {
	if (!/^[+]?(\d+(\.\d+)?)?$/.test(value)) {
		return callback(new Error('请输入数字'));
	}
	return callback();
};
const rules = reactive({
	ruleName: [{ required: true, message: '请输入显示名称', trigger: ['blur', 'change'] }],
	opreator: [{ required: true, message: '请选择操作符', trigger: ['blur', 'change'] }],
	initScore: [
		{ required: true, message: '请输入初始得分', trigger: 'blur' },
		{ validator: requiredNumber, trigger: 'blur', message: '请输入数字' },
	],
	baseNum: [
		{ required: true, message: '请输入命中基数', trigger: 'blur' },
		{ validator: requiredNumber, trigger: 'blur', message: '请输入数字' },
	],
	rate: [
		{ required: true, message: '请输入比率', trigger: 'blur' },
		{ validator: requiredNumber, trigger: 'blur', message: '请输入数字' },
	],
	max: [
		{ required: true, message: '请输入最大值', trigger: 'blur' },
		{ validator: requiredNumber, trigger: 'blur', message: '请输入数字' },
	],
});
//  操作符
const GetFieldTypes = async () => {
	let data = await GetEnumberOptions({ enumName: 'RiskOpreator' });
	state.riskOpreatorList = data.data;
};
//  新增编辑回显列表数据
const handleChange = async () => {
	if (!state.activeNames) return;
	userForm.value?.resetFields();
	const selectedItem = state.tableData.find((v: any) => v.id === state.activeNames);
	console.log(selectedItem);

	if (selectedItem.ruleName) {
		state.ruleForm = {
			ruleName: selectedItem.ruleName,
			initScore: selectedItem.initScore,
			baseNum: selectedItem.baseNum,
			opreator: selectedItem.opreator,
			rate: selectedItem.rate,
			max: selectedItem.max,
			id: selectedItem.id,
			status: selectedItem.status,
			add: false,
		};
	} else {
		state.ruleForm = {
			ruleName: '',
			initScore: '',
			baseNum: '',
			opreator: '',
			rate: '',
			max: '',
			id: '',
			status: '',
			add: true,
		};
	}
};
// 删除
const onRowDel = (id: any) => {
	ElMessageBox.confirm(`此操作将永久规则信息，是否继续?`, '提示', {
		confirmButtonText: '确认',
		cancelButtonText: '取消',
		type: 'warning',
	}).then(async () => {
		await RiskRuleDelete([id]);
		ElMessage.success('删除成功');
		resetForm();
	});
};
// 暴露变量
defineExpose({
	openDialog,
});
</script>

<style scoped lang="scss">
.system-role-container {
	.system-role-padding {
		padding: 15px;
		.el-table {
			flex: 1;
		}
	}
}
.layout-padding {
	padding: 0 15px 15px 15px !important;
	width: 100%;
}
.dialog-btn {
	text-align: center;
	padding-top: 0;
}
</style>
